package servlet;

import pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet(urlPatterns = {"/user"})
public class UserServlet extends HttpServlet {
    //alt+insert
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        List<User> users=new ArrayList<>();
        //jdbc操作数据库


            //1.加载驱动
            try {
                Class.forName("com.mysql.cj.jdbc.Driver");
                //2.获取连接
                String URL = "jdbc:mysql://127.0.0.1:3306/jdbc?characterEncoding=utf-8";
                String USER = "root";
                String PASSWORD = "ccylyw0589";
                Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
            /*if (connection != null) {
                System.out.println("连接成功");
            }*/
                //3.写sql
                String sql = "select * from user";
                //4.预编译sql
                PreparedStatement preparedStatement = connection.prepareStatement(sql);
                //5.有参设参
                //6.执行sql
                ResultSet resultSet = preparedStatement.executeQuery();
                //7.遍历结果集
                while (resultSet.next()) {
                    User user = new User();
                    user.setId(resultSet.getInt(1));
                    user.setName(resultSet.getString(2));
                    user.setPassword(resultSet.getString(3));
                    //把对象添加到集合中
                    users.add(user);
                }
                //8.
                resultSet.close();
                preparedStatement.close();
                connection.close();



                //把集合中数据存储于作用域中
                request.setAttribute("users",users);
                //打开页面
                request.getRequestDispatcher("/user.jsp").forward(request,resp);
//                request.getRequestDispatcher("/user.jsp");


            } catch (ClassNotFoundException e) {
                throw new RuntimeException(e);
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }



    }
}
